package com.gxp.util.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.support.RequestContextUtils;

public class GXPWebUtil {

	public static String handleErrorResponse(List<ObjectError> errors,
			HttpServletRequest req, HttpServletResponse resp) {

		
		try {
			boolean isAjax = "XMLHttpRequest".equals(req
					.getHeader("X-Requested-With"));
			if (isAjax) {
				List<String> messageList = new ArrayList<String>();
				ApplicationContext ctx = RequestContextUtils
						.getWebApplicationContext(req);
				for (ObjectError error : errors) {
					messageList.add(ctx.getMessage(error.getDefaultMessage(), null,
									RequestContextUtils.getLocale(req)));					
				}
				return GXPUtil.getJsonString(messageList, true, "");
			} else {
				resp.sendRedirect(req.getHeader("Referer"));
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return "";
	}
	
	public static String handleAjaxResponse(List<String> messageCode, HttpServletRequest req) {

		if (GXPUtil.isEmpty(messageCode)) {
			return GXPUtil.getJsonString("", true, "");
		} else {
			
			List<String> messageList = new ArrayList<String>();
			ApplicationContext ctx = RequestContextUtils
					.getWebApplicationContext(req);
			for (String code : messageCode) {
				messageList.add(ctx.getMessage(code, null, RequestContextUtils.getLocale(req)));
			}
			return GXPUtil.getJsonString(messageList, true, "");
		}
		
	}
	
	public static String handleAjaxResponse(String messageCode, HttpServletRequest req) {

		if (GXPUtil.isEmpty(messageCode)) {
			return GXPUtil.getJsonString("", true, "");
		} else {
			ApplicationContext ctx = RequestContextUtils
					.getWebApplicationContext(req);
			return GXPUtil.getJsonString(ctx.getMessage(messageCode, null, RequestContextUtils.getLocale(req)), true, "");
		}
		
	}
}
